import { reactive } from 'vue'

// 全局加载状态管理
export const loadingStore = reactive({
  isLoading: false,
  loadingText: '加载中...',
  requestCount: 0, // 记录当前进行中的请求数量
  
  // 显示加载
  show(text = '加载中...') {
    this.requestCount++
    this.loadingText = text
    this.isLoading = true
  },
  
  // 隐藏加载
  hide() {
    this.requestCount = Math.max(0, this.requestCount - 1)
    // 只有当所有请求都完成时才隐藏加载
    if (this.requestCount === 0) {
      this.isLoading = false
    }
  },
  
  // 强制隐藏加载（用于错误处理）
  forceHide() {
    this.requestCount = 0
    this.isLoading = false
  },
  
  // 设置加载文本
  setText(text) {
    this.loadingText = text
  }
})

// 导出便捷方法
export const showLoading = (text) => loadingStore.show(text)
export const hideLoading = () => loadingStore.hide()
export const forceHideLoading = () => loadingStore.forceHide()
export const setLoadingText = (text) => loadingStore.setText(text)

export default loadingStore